from rest_framework.serializers import ModelSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['name'] = user.first_name + '' + user.last_name
        token['is_staff'] = user.is_staff
        token['clazz'] = user.clazz.pk  # 解决班级绑定问题
        return token


class DynamicFieldModelSerializer(ModelSerializer):
    """
    动态属性 模型序列化器
    """

    def __init__(self, *args, **kwargs):
        fields = kwargs.pop('fields', [])
        super().__init__(*args, **kwargs)
        if fields:
            # 获取允许序列化的属性
            allowed = set(fields)
            # 获取配置的所有属性
            all_fields = set(self.fields)

            for field in all_fields - allowed:
                self.fields.pop(field)
